import { Message } from '@arco-design/web-react';
import qs from 'qs';
import { ResponseCode } from './constant';

export interface IResponse {
    data: any;
    code: number;
    msg: string;
}

const baseUrl = 'http://localhost:5000/v1/module';

const postFetch = (apiName: string, data, headers={}) => {
    return new Promise(async (resolve) => {
        try {
            const resp = await fetch(baseUrl + apiName, {
                method: 'POST',
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    ...headers,
                },
                body: qs.stringify(data),
            });
            const res = await resp.json();
            // 如果接口调用成功
            if (res.Result) {
                resolve(res.Result);
            } else {
                resolve(null);
                Message.error(`${apiName} error with ${res.code}, because ${res?.msg || 'unkown reason'}`)
            }
        } catch(e) {
            Message.error(`${apiName} error, because ${e || 'unkown reason'}`)
        }
    })
}

const getFetch = (apiName: string, params: Record<string, string | number>, headers={}) => {
    return new Promise(async (resolve) => {
        try {
            const resp = await fetch(linkPath(baseUrl + apiName, params), {
                method: 'GET',
                headers: {
                    ...headers
                },
            });
            const res: IResponse = await resp.json();
            if (res.code === ResponseCode.Success) {
                resolve(res?.data);
            } else {
                resolve(null);
                Message.error(`${apiName} error with ${res.code}, because ${res?.msg || 'unkown reason'}`)
            }
        } catch(e) {
            Message.error(`${apiName} error, because ${e || 'unkown reason'}`)
        }
    })
}

const linkPath = (url: string, params: Record<string, string | number>) => {
    if (Object.prototype.toString.call(params).includes('object')) {
        const realPath = url + '?' + Object.keys(params).reduce((prev, currentKey) => {
            prev = prev + `${currentKey}=${params[currentKey]}&`
            return prev;
        }, '')
        return realPath.slice(0, realPath.length - 1);
    } else return url;
}

export {
    postFetch,
    getFetch,
}